package com.fjzn.detect.advice;

import com.alibaba.fastjson.JSON;
import com.fjzn.detect.common.annotation.EncryptResp;
import com.fjzn.detect.common.enums.other.YesNo;
import com.fjzn.detect.core.result.ResponseResult;
import com.fjzn.detect.core.utils.sign.RSAUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;
import java.util.Optional;

/**
 * 加密切面
 *
 * @author yzh
 * @since 2021年04月26日09:09:04
 */
@RestControllerAdvice
public class EncodeResponseBodyAdvice implements ResponseBodyAdvice<ResponseResult<Object>> {

    private final String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKGHhoYEWjeuYRSohDAzcbQ1cD+Fi0+7pvxMBK81Kwxgj30fq0D6MBMDdNmlpSVpXV2eg9Qd1VqqmCRT21154heJ2CMQg5LyV1OuOp41SIJJ35jdMKtNSSocqsyHMoOrNDqtLrQahRwkotlBAnvbg+8RqCYO11ex08zfupi0SrDHAgMBAAECgYBgiP1VlL5SLq4oSXoO0H/wwkseO3KBqVVnzQqzp2Pd1suKbOXNRHh8tIEeHgfvruO0sqp4l4fN0sxwUYl1eQUsMjEN8KuRb34DCRl9voSmzyihQO/VFG+ByTmsbv6O9Ve/2Fe5gG3HdZB0ZBeCIrqazIhxIJDfQN+Q311yPKa3sQJBAPhQZB76iMaZwjvF7wonTc567NO3ep/OOVk9GtB5F1OJxVsPOHptI4f2A8wUthVHaTbKCcWXV+qpXySF8zsmrVkCQQCmh3bGBWUo40jc4UG1RkGP3+NeOFhh/1JNt3MvV4GIfhcEYp92PbYeLPzaVlelVCrF9qs8yR8YHDOAYOeu8+sfAkAmtxIFKnas0EhSXXf5k0s0SEIoeFDsHZEfcsF9g4O5iJ92pRbfL6j8h8Trysbg5nNnEXUYk5IniiTFYwUbUdpxAkBDrJ9W/9BJWnw8zwnN6hwwpNKYcptwT7sZvCiCH7STTHJ8JLwa6B8/ihbDf/0kQd0UEBcsn6sUODmxvS/KCHQPAkEAmuPXRBu0lHFeAAtBG8RWR2gzU0C4nujEb2x1qZ7iNEjHpfKwoup8zd4FvBs8BlJ4wIONYD5VB7sdQtwdLlMT3Q==";

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.hasMethodAnnotation(EncryptResp.class);
    }

    @Override
    public ResponseResult<Object> beforeBodyWrite(ResponseResult<Object> result, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Optional.ofNullable(result).ifPresent(e ->{
            if(Objects.nonNull(e.getData())){
                e.setEncode(YesNo.YES);
                e.setData(RSAUtils.encryptPriKey(JSON.toJSONString(e.getData()),privateKey));
            }
        });
        return result;
    }
}
